package filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Locale;

@WebFilter(urlPatterns = "/*")
public class RequestFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        request.setCharacterEncoding("utf-8");
        String requestPath = request.getRequestURI();
        System.out.println("拦截地址 ---->" + requestPath);

        switch(requestPath.substring(requestPath.indexOf(".") + 1)){
            case "js" -> response.setContentType("application/javascript;charset=utf-8");
            case "css" -> response.setContentType("text/css");
            case "png" -> response.setContentType("image/png");
            default -> response.setContentType("text/html;charset=utf-8");
        }

        if(requestPath.contains("page") ){
            request.getRequestDispatcher(requestPath + ".jsp").forward(request,response);
            return;
        }else if(requestPath.contains("service")){
            response.setContentType("application/json;charset=utf-8");
            String[] path = requestPath.split("/")[2].split("_");

            path[1] = path[1].substring(0,1).toUpperCase(Locale.ROOT) + path[1].substring(1);
            request.setAttribute("method",path[0] + path[1]);

            path[0] = path[0].substring(0,1).toUpperCase(Locale.ROOT) + path[0].substring(1);
            request.getRequestDispatcher("/" + path[0]).forward(request,response);
            return;
        }
        filterChain.doFilter(request,response);
    }
}
